package org.example.mall4j.Service.impl;


import org.example.mall4j.Service.UserService;
import org.example.mall4j.dao.UserMapper;
import org.example.mall4j.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service //注册到SprngBoot中的服务组件
public class UserServiceimpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    //实现按照姓名查找用户
    @Override
    public SysUser findByName(String name) {
        return userMapper.getUserInfoByUserName(name);
    }


    //在数据库中，新增一位用户，且密码以加盐形式保存
    @Override
    public int insert(SysUser user) {
        //存在数据库中的密码应该为密文
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userMapper.insert(user);
    }

    //返回认证用户信息对象。
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //根据姓名查找用户
        SysUser user = findByName(name);
        if(user==null){
            System.out.println("没有此用户");
            return null;
        }
        else {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        return user; //此时的user，是被UserDetails包装过具有可认证身份信息的用户对象。
    }
}

